package com.suzhe.ymall.base.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.domain.ThumbImageConfig;
import com.github.tobato.fastdfs.service.FastFileStorageClient;

import com.suzhe.ymall.base.config.UploadProperties;
import com.suzhe.ymall.base.vo.ImageVo;
import com.suzhe.ymall.common.exception.YMallException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Slf4j
@Service
public class UploadServcice {

    @Autowired
    private UploadProperties prop;

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private ThumbImageConfig thumbImageConfig;

    public ImageVo upload(MultipartFile file) {
        ImageVo imageVo = new ImageVo();
        // 1、文件的校验
        // 1.1.校验文件类型
        String contentType = file.getContentType();
        if (!prop.getAllowTypes().contains(contentType)) {
            throw new YMallException("不合理的文件类型");
        }
        // 1.2.校验数据内容
        BufferedImage image = null;
        try {
            image = ImageIO.read(file.getInputStream());
        } catch (IOException e) {
            log.error("文件上传失败：文件名：{}", file.getOriginalFilename(), e);
        }
        if (image == null) {
            log.error("文件上传失败：文件名：{}", file.getOriginalFilename());
            throw new YMallException("文件格式错误");

        }
//        StorePath storePath = null;
        try {
//            storePath = this.storageClient.uploadFile(
//                    file.getInputStream(), file.getSize(), getExtension(file.getOriginalFilename()), null);
            StorePath storePath = this.storageClient.uploadImageAndCrtThumbImage(file.getInputStream(),
                    file.getSize(), getExtension(file.getOriginalFilename()), null);
            // 获取缩略图路径
            String thumPath = thumbImageConfig.getThumbImagePath(storePath.getFullPath());
            imageVo.setUrl(prop.getBaseUrl() + storePath.getFullPath());
            imageVo.setThumbUrl(prop.getBaseUrl() + thumPath);
        } catch (IOException e) {
            log.error("文件上传失败：文件名：{}", file.getOriginalFilename(), e);
            throw new YMallException("文件格式错误");
        }
        // 3、生成图片地址

        return imageVo;
    }

    public String getExtension(String fileName) {
        return StringUtils.substringAfterLast(fileName, ".");
    }
}
